/**
* @Title: warning_ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @date 2014年10月27日 下午4:43:38
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('BackCaseReviewProjectCtrl', ['$scope','CommunityService','WarningAddService','CaseAuditDispathReviewDetailResultService','CaseAuditProjectAddService','CaseCommonService','$http','$modal','CaseReviewProjectService','$state','BaseURL','Modal','FwaTabsetService','$stateParams','WarningScreenService',
	                                function($scope,CommunityService,WarningAddService,CaseAuditDispathReviewDetailResultService,CaseAuditProjectAddService,CaseCommonService,$http,$modal,CaseReviewProjectService,$state,baseUrl,Modal,fwaTabsetService,$stateParams,WarningScreenService){
    $scope.communityService = CommunityService;
    CommunityService.initCodeListDatas();

    $scope.communityService = CommunityService;
    var currentDeadLine = '';
    $scope.$watch('communityService.caseDate',function(v){
        angular.forEach(v,function(totalCheck,i){
            if(totalCheck.code=='01')
            {
                var caseLimitDate = parseInt(totalCheck.name);
                CommunityService.initDate("yyyy-mm-dd").success(function(res){
                    var currentDate = new Date(res.formatDate);
                    currentDate.setDate(currentDate.getDate() + caseLimitDate);
                    currentDeadLine = currentDate.format('yyyy-MM-dd');
                });
            }
        });
    });
		$scope.showDeadLine=false; //展现截止日期的按钮
		
		
		
		
		
              $scope.requestParam = {
	                page:"1",
	                pageSize:"20"
	            };
        $scope.UrlParams = $stateParams;
		$scope.CaseReviewProjectService = CaseReviewProjectService;

		$scope.selectedTab = $scope.tabs[0];
		$scope.currentTabIndex = 0;

        $scope.problemtab=[ {label:'事件处理',id:0,url:'views/hcpms/audit/caseAduitDispathDealProblem.html'},
            {label:'调查结果',id:1,url:'views/hcpms/audit/caseAduitProjectDetails.html'},
            {label:'稽核项目',id:2,url:'views/hcpms/audit/caseReviewPorject_view.html'},
            {label:'稽核结果',id:3,url:'views/hcpms/audit/backCaseReviewProjectDetails.html'}];

        $scope.tabClicks = function(tab) {
            $scope.selectedTabs = tab;
            $scope.tabIndex=tab.id;

            if($scope.tabIndex==0){
                initdealPorblemData();
            }
            if($scope.tabIndex==1){
                initProblem();
            }
            if($scope.tabIndex==2){
                //选中tab抛出改变窗口事件
                setTimeout(function(){
                    $(window).trigger('resize');
                },0);
                auditProject();
            }
            if($scope.tabIndex==3){
                gettotalDeduction();
            }
        }
		
		//初始化请求参数
         $scope.caseCode="";
        var params = function (){
            var problemNo = "";
            var  caseCode="";
            if($stateParams.problemNo && !angular.isUndefined($stateParams.problemNo) ){
                problemNo = $stateParams.problemNo;
            }
            if($stateParams.caseCode && !angular.isUndefined($stateParams.caseCode) ){
                caseCode = $stateParams.caseCode;
            }
            var params = {
                caseCode:caseCode,
                problemNo:problemNo,
                page:$scope.requestParam.page,
                pageSize:$scope.requestParam.pageSize
            }
            return params;
        }

        /**
         * 初始化医疗机构数据
         */
        function initdealPorblemData(){
            var parameter=params();
            CaseReviewProjectService.loadDealProblemData(parameter).success(function(response){
                 $scope.treatmentOpinion = response.result.treatmentOpinion;
                 $scope.auditOpinion = response.result.auditOpinion;
            });
        }
        function  initProblem(){
            var parameter=params();
            CaseReviewProjectService.queryOpinionData(parameter).success(function(response){
                $scope.treatmentOpinions=response.result.treatmentOpinion;
                $scope.auditOpinions=response.result.auditOpinion;
                $scope.audit=response.result.audit;
            });
        }
        $scope.columns = [
            {label:'项目名称',map:'projectName',width:'20%'},
            {label:'结算方式',map:'treatTypeName',width:'20%'},
            {label:'不合理费用',map:'deductionAmmountStr',width:'20%'},
            {label:'备注',map:'remark',width:'40%'}
                 ];
        /**
         * 稽核项目
         */
        $scope.tableData=[];
        function auditProject()
        {
            var parameter=params();
            CaseReviewProjectService.queryAuditProject(parameter).success(function(response)
            {
                $scope.tableData=response.result.auditProjectList;
                $scope.ammountCounts();
            });
        }

        /**
         * 初始化医疗机构数据和医护人员信息和参保人信息
         */
        $scope.medicalCode='';
        function initMedicalData(){
            var parameter={
            		problemNo:$stateParams.caseCode
            };
            CaseCommonService.loadMedicalInfoList(parameter).success(function(response){
                $scope.medicalData2=response.medicalBean.medicalList;
                if($scope.medicalData2.length>0)
                {
                    if($scope.medicalData2[0].medicalCode)
                    {
                        $scope.medicalCode=$scope.medicalData2[0].medicalCode;
                    }
                }
                $scope.staffData2=response.staffBean.staffList;
                $scope.insuranceData2=response.insuranceBean.insuranceList;
                
                
                CaseCommonService.initStaffAndInsuranceTempList($scope);
				//更新当前页面数据
     		   WarningScreenService.findPointCutTempScose(
     				   WarningAddService.warningMarks,$stateParams.caseCode,'02',
     				   $scope.medicalData2[0],$scope.staffData2,$scope.insuranceData2);
                
                
            });
        }
         $scope.caseObj={};
         var caseObj={};
        /**
         * 初始化事件数据对象
         */
        $scope.initProblemData= function(){
            var parameter=params();
            CaseCommonService.loadCaseData(parameter).success(function(response){
                $scope.caseObj = response.result.case1;
                caseObj=$scope.caseObj;
            });
        }
        /**
         * 获取稽核结论详情
         */
        $scope.caseOpinionObj={};
        $scope.caseOpinionObjShow=false;
        $scope.auditDatail=null;
        $scope.tempFlag='';//暂存标识：1，暂存；0，保存，2，退回岗位不同时
        function gettotalDeduction()
        {
            var parameter=params();
            parameter.problemNo=parameter.caseCode;
            var parameters={businessId:$stateParams.caseCode,
                moduleType:'jhModule',
                childModuleType:'review',
                businessType:'12'};
            CaseAuditProjectAddService.loadOpinionList(parameter).success(function(response){
                if(response.result){
                    if(response.result.treatmentOpinion)
                    {
                        $scope.caseOpinionObjShow=true;
                        $scope.caseOpinionObj=response.result.treatmentOpinion;
                        $scope.caseOpinionObj.auditDate= $scope.caseObj.auditDate;
                        $scope.caseOpinionObj.periodBeginDate=$scope.caseObj.periodBeginDate;
                        $scope.caseOpinionObj.totalDeduction=$scope.caseObj.totalDeductionStr;
                        $scope.caseOpinionObj.periodEndDate=$scope.caseObj.periodEndDate;
                        $scope.caseOpinionObj.auditSummary=$scope.caseObj.auditSummary;

                        $scope.reviewDatail.oldOpinionDesc=$scope.caseOpinionObj.opinionDesc;
                    }
                    if(response.result.auditOpinion)
                    {
                        $scope.reviewDatail=response.result.auditOpinion;
                        $scope.reviewDatail.originalOpinionDesc=$scope.reviewDatail.opinionDesc;
                        
                        var opinion=$scope.reviewDatail.opinionState;
        				if(opinion && opinion=='1'){ //同意
        					$scope.showDeadLine=true;
        				}else if(opinion && opinion=='0'){ //保留意见
        					$scope.showDeadLine=false;
        				}
                    }

                    if(response.result.audit)
                    {
                        $scope.auditDatail=response.result.audit;
                    }
                    if(response.result.tempFlag)
                    {
                        $scope.tempFlag=response.result.tempFlag;
                    }
                }
                CaseAuditDispathReviewDetailResultService.loadStorageData(parameters).success(function(response)
                {
                    if(response.result)
                    {
                        $scope.caseOpinionObj.opinionDesc= response.result.newOpinionDesc;
                        $scope.reviewDatail.oldOpinionDesc= $scope.caseOpinionObj.opinionDesc;
                        if(response.result.opinionState && response.result.opinionState=='1'){ //同意
                            $scope.reviewDatail.opinionState= response.result.opinionState;
                            $scope.reviewDatail.affirmDeadline=response.result.affirmDeadline;
                            $scope.showDeadLine=true;
                        }else if(response.result.opinionState && response.result.opinionState=='0'){ //保留意见
                            $scope.reviewDatail.opinionState= response.result.opinionState;
                            $scope.showDeadLine=false;
                        }
                        $scope.reviewDatail.opinionDesc=response.result.opinionDesc;
                    }
                });
            });
        }
        
        /**复合意见选择监听函数***/
		$scope.selectChangeFun=function(){
			
			if($scope.reviewDatail){
				var opinion=$scope.reviewDatail.opinionState;
				if(opinion && opinion=='1'){ //同意
					$scope.showDeadLine=true;
					$scope.reviewDatail.affirmDeadline=currentDeadLine;
				}else if(opinion && opinion=='0'){ //保留意见
					$scope.showDeadLine=false;
				}
			}
			
		}
       


		//隐藏扣分以及删除按钮
		$scope.mouseoutShow = function(data){
			data.show = false;
		}
		
        //显示扣分以及删除按钮
		$scope.mouseoverShow = function(data){
			data.show = true;
		}
        /**
         * 返回
         */
        $scope.goBack = function () {
		   	WarningAddService.warningMarks = WarningAddService.warningMarkTemps;//初始化扣分参数

            if($stateParams.urlFlag){
                var urlFlag =  $stateParams.urlFlag;
                fwaTabsetService.closeTab('caseAudit','workingArea.transactorle',{urlFlag:$stateParams.urlFlag});
            }else
            {
                $state.go("caseAudit.caseAuditList");
            }
        };

        $scope.reviewDatail={};
        $scope.loading = false;
        $scope.submitForOpinion=function(flag)
        {
            //判断是否录入稽核告知函
            if(check())
            {
                $scope.loading = true;
                $scope.reviewDatail.problemNo=$scope.UrlParams.caseCode;
                $scope.reviewDatail.newOpinionDesc=$scope.caseOpinionObj.opinionDesc;
                $scope.reviewDatail.onlySave=flag;
                $scope.reviewDatail.flag='1';
                $scope.reviewDatail.opinion= $scope.reviewDatail.opinionState;
                $scope.reviewDatail.tempFlag=$scope.tempFlag;//暂存标识：1，暂存；0，保存，2，退回岗位不同时
                $scope.reviewDatail.warnMarkTempDetails=WarningAddService.warningMarks;
                var parameter=$scope.reviewDatail;
                CaseReviewProjectService.addcaseInfo(parameter).success(function(data){
                    if(data.state=='true')
                    {
                        if(flag=='0')
                        {
                            $scope.goBack();
                        }
                        Modal.alert(data.msg);
                        WarningAddService.warningMarks = [];
                        
                    	//更新当前页面数据
              		   WarningScreenService.findPointCutTempScose(
              				   WarningAddService.warningMarks,$stateParams.caseCode,'02',
              				   $scope.medicalData2[0],$scope.staffData2,$scope.insuranceData2);
                    }else
                    {
                        Modal.alert(data.msg);
                    }
                    $scope.loading = false;
                });
                if(flag=='0')
                {
                    $scope.saveReallyStaffAndInsuarnceInfo();
                }else
                {
                    $scope.saveStaffAndInsuarnceInfo();
                }
            }

        }
        /**
         * 医疗机构扣分事件
         */
        $scope.$on('fwaInvolve.medicalDeduction',function(e,v){
            $scope.marking (1,v, v.medicalCode, v.orgType);
        });
        /**
         * 医务人员扣分事件
         */
        $scope.$on('fwaInvolve.staffDeduction',function(e,v){
            $scope.marking(2,v,$scope.medicalCode,'');
        });
        //扣分 mark：1.机构扣分，2.医务人员扣分，3参保人员扣分,data:数据集合
        $scope.marking = function(mark,data,medicalCode,orgType){
            var medicalCodeTemp=null;
            if(medicalCode&&!angular.isUndefined(medicalCode)){
                medicalCodeTemp = medicalCode;
            }
            if(mark != 1 && medicalCodeTemp == null){
                Modal.alert("请先增加医疗机构信息！");
                return null;
            }else{
                medicalCode = medicalCodeTemp;
            }
            markData(mark,data,medicalCode,orgType);//扣分数据参数加载
            var modalInstance = $modal.open({
                templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningDeductionDialog_view.html',
                backdrop:'static',
                size:'sm',
                scope: $scope,
                //					  scope:scope,
                controller: 'WarningDeductionDialogCtrl'
            });
            //接收返回数据
            modalInstance.result.then(function(item) {
                if (!WarningAddService.warningMarks) {
                    WarningAddService.warningMarks = [];
                }
                WarningAddService.warningMarks = item;
                
                
                //更新当前页面数据
     		   	WarningScreenService.findPointCutTempScose(
     		   		item,$stateParams.caseCode,'02',
     		   	$scope.medicalData2[0],$scope.staffData2,$scope.insuranceData2);
                
                
            });
        }
        //扣分数据参数加载
        var markData = function(mark,data,medicalCode,orgType){
            WarningAddService.mark = mark;
            WarningAddService.warningMarkData = {
                orgType:orgType,//0.机构，1.药店
                medicalCode:medicalCode,//medicalCode:所属机构编号
                code:data.selfCode,//code:编号
                name:data.name,//name:名称
                caseType:'02',//案件类型caseType：01.预警,02.稽核
                caseNo: $stateParams.caseCode,//事件编号
                happenDate: $scope.caseObj.auditDate,//稽核时间
                punishDateStart: $scope.caseObj.periodBeginDate,// 稽核开始日期
                punishDateEnd: $scope.caseObj.periodEndDate,// 稽核结束日期
                warningMarks:WarningAddService.warningMarks
            };
        }

        function check()
        {
            if(!$scope.reviewDatail.opinionDesc)
            {
                Modal.alert('意见说明为必填项！');
                return false;
            }else  if(!$scope.reviewDatail.opinionState)
            {
                Modal.alert('复核意见为必填项！');
                return false;
            }
            else  if($scope.caseOpinionObjShow && !$scope.caseOpinionObj.opinionDesc)
            {
                Modal.alert(' 处理意见为必填项！');
                return false;
            }else if($scope.reviewDatail.opinionState && $scope.reviewDatail.opinionState=='1'){ //同意
            	if(!$scope.reviewDatail.affirmDeadline){
            		Modal.alert('截止日期不能为空!');
                    return false;
            	}
            	
            }
            return true;
        }

        /**
         * 医疗机构扣分
         */
        $scope.pointsMedical=function(id)
        {
            var problemNo=$stateParams.caseCode;
            fwaTabsetService.selectTab('pointsMedical',{id:id,problemNo:problemNo},false);
        }

        /**
         * 调新增医务人员的回调函数
         *  parameter={
        * taskCode:'',
        * taskType:'',1事件,2案件
        * targetType:'',对象类型(1-医疗机构2-医生3-参保人)
        * targetCode:''
        * }
         */
        $scope.callStaffFun=function(array){
        	  CaseCommonService.addTempStaffList(array,$scope);
        }
        /**
         * 调新增参保人员的回调函数
         */
        $scope.callInsuranceFun=function(array){
        	CaseCommonService.addTempInsuranceListInfo(array,$scope);
        }


        /**
         * 新增医护人员事件
         */
        $scope.$on('fwaInvolve.staffAdd',function(){
            CaseCommonService.addStaffFun($scope);
        });

        /**
         * 新增参保人员事件
         */
        $scope.$on('fwaInvolve.insuranceAdd',function(){
            CaseCommonService.addInsuranceFun($scope);
        });

        /**
         * 医务人员删除
         */
        $scope.$on('fwaInvolve.staffDel',function(e,data){
        	 Modal.confirm('确认删除医务人员'+data.name+'吗？',function(){
 				WarningScreenService.deleteMark(WarningAddService.warningMarks,2,data);//mark:1.机构，2.医务人员，3.参保人
 				 CaseCommonService.deleteTempStaffList(data,$scope);
 			});
     	   
        });

        /**
         * 参保人员删除
         */
        $scope.$on('fwaInvolve.insuranceDel',function(e,data){
        	  Modal.confirm('确认删除参保人员'+data.name+'吗？',function(){
  				WarningScreenService.deleteMark(WarningAddService.warningMarks,3,data);//mark:1.机构，2.医务人员，3.参保人
  				 CaseCommonService.deleteTempInsuranceInfoList(data,$scope);
  			});
        });
        
        /**
         * 点击医疗机构量事件
         * 
         */
        $scope.$on('fwaInvolve.medicalCountClick',function(){
     	   CaseCommonService.viewMedicalDetail($scope);
        });

        /**
         * 点击医务人员总数量事件
         */
        $scope.$on('fwaInvolve.staffCountClick',function(){
        	CaseCommonService.viewStaffList($scope);
        });
        
        /**
         * 点击参保人总数量事件
         */
        $scope.$on('fwaInvolve.insuranceCountClick',function(){
        	CaseCommonService.viewInsurList($scope);
        });
        
        /**
         * 根据案件编号获取稽核项目不合理费用总额
         */
       /* $scope.ammountCount=function()
        {
            var parameter={caseCode:$scope.UrlParams.problemNo};
            CaseReviewProjectService.getammountCount(parameter).success(function(data){
                $scope.ammountCount=(data.ammount/100).toFixed(2);
            });
        }*/
        $scope.ammountCount = "0.00";
        //计算合计金额
         $scope.ammountCounts=function() {
            var countNum = 0;
            angular.forEach($scope.tableData,function(data,index){
                countNum = countNum + parseFloat(data.deductionAmmount) * 100;
            });
            $scope.ammountCount = (countNum/100).toFixed(2);
        }
        /**
         * 查看案件来源
         */
        $scope.$on('fwaAuditLeft.showModal',function(){
            $scope.caseObj=caseObj;
            CaseCommonService.showCaseFromSourceDialog($scope);
        });
        /**
         * 查看稽核项目
         */
            //弹窗
        $scope.ShowAuditProject = function(){
            $modal.open({
                templateUrl:'auditProjectAdd_view.html',
                backdrop:'static',
                size:'sm',
                controller: function($scope, $modalInstance,Modal,CommunityService,$stateParams){
                    $scope.communityService = CommunityService;
                    CommunityService.initCodeListDatas();

                    $scope.auditProject = {};

                    //关闭弹窗
                    $scope.onOk = function() {
                        $modalInstance.dismiss();
                    }
                    //确定事件
                    $scope.confirm = function() {
                        if(!$scope.auditProject.treatType){
                            Modal.alert("就诊类型为必填项！");
                            return false;
                        }
                        if(!$scope.auditProject.deductionAmmount){
                            Modal.alert("不合理费用为必填项");
                            return false;
                        }
                        var money= /^[0-9]{0,10}(\.[0-9]{2})$/;
                        if($scope.auditProject.deductionAmmount && !money.test($scope.auditProject.deductionAmmount))
                        {
                            Modal.alert('不合理费用为十位数以内的小数，小数点后请保留两位小数！');
                            return false;
                        }
                        if(!$scope.auditProject.invoiceType){
                            Modal.alert("发票类型为必填项！");
                            return false;
                        }
                        $scope.auditProject.caseCode= $stateParams.caseCode;
                        CaseReviewProjectService.addAuditProject($scope.auditProject).success(function(data){
                            if (data.state == '0') {
                                Modal.alert(data.msg);
                                $modalInstance.close($scope.auditProject);
                            } else {
                                Modal.alert("添加失败！");
                            }
                        });
                    }
                }
            }).result.then(function(item) {
                    if (item) {
                        $scope.tabClicks($scope.problemtab[2]);
                    }
                });
        }
        /**
         * 新增稽核告知函
         */
            //弹窗
        $scope.auditNotification = function(){
        	ininAuditNotifiaction();
        }
        
        
        
        
        
        function ininAuditNotifiaction(){
           	var parameter={
           			caseCode:$stateParams.caseCode
           	};
             CaseCommonService.loadAuditNotifionInfo(parameter).success(function(response){   
           	  
           	  
           	  
    				$scope.reportBean=response.reportBean;
    				$scope.caseDetail=response.tellReportBean;
    				
    				$scope.reportBean.auditRang={
    		       			   start:$scope.reportBean.auditStart,
    		       			   end:$scope.reportBean.auditEnd
    		       	      };
    				
    				CaseCommonService.showCaseAuditTellReportDialog($scope);
    			});
           }
        
        initMedicalData();
        $scope.ammountCounts();
        $scope.initProblemData();
        $scope.tabClicks($scope.problemtab[3]);

        /**
         * 对医务人员和参保人员的暂存信息保存
         */
        $scope.saveStaffAndInsuarnceInfo=function(){
            $scope.saveType="temp";
            saveStaffListInfo();
            saveInsuranceInfo();
        }


        /**
         * 对医务人员和参保人员的真实数据信息保存
         */
        $scope.saveReallyStaffAndInsuarnceInfo=function(){
            $scope.saveType="save";
            saveStaffListInfo();
            saveInsuranceInfo();
        }
        
 	   /**
 	    * 暂存的时候对医务人员进行的保存
 	    */
        function saveStaffListInfo(){
 	   CaseCommonService.saveTempStaffListInfo($scope,'2','2',$stateParams.caseCode);
 	   
        }
        
        /**
 	    * 暂存的时候对参保人员进行的保存
 	    */
        function saveInsuranceInfo(){
     	   CaseCommonService.saveTempInsuranceListInfo($scope,'2','3',$stateParams.caseCode);
        }
        
        
   }]);
})();
